import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

class ProfilePage extends StatefulWidget {

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final UserProfile _user = UserProfile(
    name: '张小钉',
    position: '高级产品经理 @ 阿里巴巴',
    avatar: 'https://example.com/avatar.png',
    enterprise: '阿里巴巴集团',
    dingId: 'ding123456789',
    qrCode: 'https://example.com/qrcode.png',
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 0, // 设置为0就不会显示了
        // title: const Text('我'),
        // actions: [
        //   IconButton(icon: Icon(Icons.add), onPressed: () {}),
        // ],
      ),
      body: CustomScrollView(
        slivers: [
          _buildProfileHeader(context),
          _buildFunctionGrid(context),
          _buildEnterpriseSection(),
          _buildSettingsList(),
          _buildFooter(),
        ],
      ),
    );
  }

  SliverAppBar _buildProfileHeader(BuildContext context) {
    return SliverAppBar(
      expandedHeight: 202, // 这个高度还是需要的，但是容易出问题呢 2025-03-15
      flexibleSpace: FlexibleSpaceBar(
        background: Column(
          children: [
            _buildUserInfo(context),
            _buildQuickActions(context),
          ],
        ),
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(16),
      child: Row(
        children: [
          CircleAvatar(
            radius: 36,
            backgroundImage: CachedNetworkImageProvider(_user.avatar),
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(_user.name,
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                SizedBox(height: 4),
                Text(_user.position,
                    style: TextStyle(color: Colors.grey[600])),
                SizedBox(height: 8),
                Row(
                  children: [
                    Icon(Icons.business, size: 16, color: Colors.grey),
                    SizedBox(width: 4),
                    Text(_user.enterprise,
                        style: TextStyle(color: Colors.grey[600])),
                  ],
                ),
              ],
            ),
          ),
          IconButton(
            icon: Icon(Icons.qr_code_scanner),
            onPressed: () => _showQRCode(context),
          ),
        ],
      ),
    );
  }

  Widget _buildQuickActions(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildActionItem(context, Icons.message, '消息'),
          _buildActionItem(context, Icons.mail, '邮箱'),
          _buildActionItem(context, Icons.cloud, '钉盘'),
          _buildActionItem(context, Icons.settings, '设置'),
        ],
      ),
    );
  }

  Widget _buildActionItem(BuildContext context, IconData icon, String label) {
    return Column(
      children: [
        IconButton(
          icon: Icon(icon, color: Theme.of(context).primaryColor),
          onPressed: () => _handleAction(label),
        ),
        Text(label, style: TextStyle(fontSize: 12)),
      ],
    );
  }

  Widget _buildFunctionGrid(BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.all(16),
      sliver: SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 16,
          crossAxisSpacing: 16,
          childAspectRatio: 0.9,
        ),
        delegate: SliverChildListDelegate([
          _buildGridItem(context, '智能工资条', Icons.payment),
          _buildGridItem(context, '考勤打卡', Icons.access_time),
          _buildGridItem(context, '智能审批', Icons.assignment_turned_in),
          _buildGridItem(context, '差旅出行', Icons.airplanemode_active),
          _buildGridItem(context, '学习中心', Icons.school),
          _buildGridItem(context, '健康上报', Icons.favorite),
          _buildGridItem(context, '智能会议室', Icons.meeting_room),
          _buildGridItem(context, '更多', Icons.more_horiz),
        ]),
      ),
    );
  }

  Widget _buildGridItem(BuildContext context, String title, IconData icon) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CircleAvatar(
          radius: 20,
          child: Icon(icon, size: 24),
          backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
          foregroundColor: Theme.of(context).primaryColor,
        ),
        SizedBox(height: 8),
        Text(title,
          style: TextStyle(fontSize: 12),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildEnterpriseSection() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(16),
        margin: EdgeInsets.only(bottom: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('企业信息', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            SizedBox(height: 12),
            _buildInfoItem('企业认证', '已认证', Icons.verified),
            _buildInfoItem('DING ID', _user.dingId, Icons.tag),
            _buildInfoItem('安全等级', '企业级防护', Icons.security),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoItem(String title, String value, IconData icon) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Icon(icon, color: Colors.grey[600]),
          SizedBox(width: 12),
          Text(title, style: TextStyle(fontSize: 14)),
          Spacer(),
          Text(value, style: TextStyle(color: Colors.grey[600])),
        ],
      ),
    );
  }

  Widget _buildSettingsList() {
    return SliverList(
      delegate: SliverChildListDelegate([
        _buildListTile('账号与安全', Icons.lock),
        _buildListTile('通用设置', Icons.settings),
        _buildListTile('隐私设置', Icons.privacy_tip),
        _buildListTile('帮助与反馈', Icons.help),
        _buildListTile('关于钉钉', Icons.info),
      ]),
    );
  }

  Widget _buildListTile(String title, IconData icon) {
    return Container(
      color: Colors.white,
      child: ListTile(
        leading: Icon(icon, color: Colors.grey[600]),
        title: Text(title),
        trailing: Icon(Icons.chevron_right),
        onTap: () => _navigateToSettings(title),
      ),
    );
  }

  Widget _buildFooter() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            Text('当前版本 6.5.20', style: TextStyle(color: Colors.grey)),
            SizedBox(height: 8),
            OutlinedButton(
              child: Text('联系客服'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }

  void _showQRCode(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            AppBar(
              title: Text('我的二维码'),
              automaticallyImplyLeading: false,
              actions: [
                IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.all(24),
              child: CachedNetworkImage(
                imageUrl: _user.qrCode,
                width: 200,
                height: 200,
              ),
            ),
            Text('扫一扫二维码添加我', style: TextStyle(color: Colors.grey)),
            SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  void _handleAction(String label) {
    // 处理点击事件
  }

  void _navigateToSettings(String title) {
    // 导航到设置页面
    Navigator.pushReplacementNamed(context, '/security'); // 这个要使用有状态的widget
  }
}

// 数据模型
class UserProfile {
  final String name;
  final String position;
  final String avatar;
  final String enterprise;
  final String dingId;
  final String qrCode;

  UserProfile({
    required this.name,
    required this.position,
    required this.avatar,
    required this.enterprise,
    required this.dingId,
    required this.qrCode,
  });
}
